package com.android.BluethootChess.connectivity;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;

import android.graphics.Point;

import com.android.BluethootChess.util.Utils;

public class WirelessClient implements IComunication {
	private Socket socket;
	private DataInputStream recv;
	private DataOutputStream send;

	public WirelessClient(int port, String IP) {
		Utils.logFile("Start client pe port = " + port);

		try {
			InetAddress address = InetAddress.getByName(IP);// Inet4Address.getLocalHost();
			socket = new Socket(address.getHostName(), port);

			recv = new DataInputStream(socket.getInputStream());
			send = new DataOutputStream(socket.getOutputStream());

			Utils.logFile("Local IP: "
					+ socket.getLocalAddress().getHostAddress());

		} catch (Throwable e) {
			Utils.logFileError(e);
		}
	}

	public void sendString(String string) {
		try {
			send.writeUTF(string.toString());
		} catch (Throwable e) {
			Utils.logFileError(e);
		}
	}

	public String recvString() {
		String result = "";
		try {
			result = recv.readUTF();
			Utils.logFile("S-a primit de la server: " + result);
		} catch (Throwable e) {
			Utils.logFileError(e);
		}

		return result;
	}

	/**
	 * Primeste o lista de puncte de la un server.
	 * */
	public Point[] receivePoints() {
		Point points[] = null;
		int[] coords = null;

		try {
			int lenght = recv.readInt();
			points = new Point[lenght];
			coords = new int[lenght * 2];

			for (int i = 0; i < coords.length; i++) {
				coords[i] = recv.readInt();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		points[0] = new Point(coords[0], coords[1]);
		points[1] = new Point(coords[2], coords[3]);

		return points;
	}

	/**
	 * Trimite o lista de puncte la un server.
	 * 
	 * @param points
	 *            - lista de puncte
	 * */
	public void sendPoints(Point[] points) {
		try {
			send.writeInt(points.length);
			for (int i = 0; i < points.length; i++) {
				send.writeInt(points[i].x);
				send.writeInt(points[i].y);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Point[] getPointsFromServer() {
		
		return null;
	}

	@Override
	public void sendPointsAsString(Point[] points) {
		// TODO Auto-generated method stub
		
	}

}
